package login

import (
	"moko/internal/models/account"
	"moko/internal/request/parameter"
	"moko/internal/response"
	"moko/utility"
	"net/http"
	"strconv"
	"time"
)

type UserLogin struct{}

// Register 用户注册
func (us *UserLogin) Register(params parameter.Register) response.Response {
	userInfo := account.GetUserByMobile(params.Mobile)
	if userInfo.ID != 0 {
		return response.CommonResponse[bool]("该用户已存在", http.StatusBadRequest, false)
	}

	account.CreateUser(account.Users{
		Username: params.Username,
		Password: utility.MD5String(params.Password),
		Mobile:   params.Mobile,
		LastTime: time.Now(),
	})

	return response.CommonResponse[bool]("注册成功", http.StatusOK, true)
}

// Login 用户登录
func (us *UserLogin) Login(params parameter.Login) response.Response {
	var userQuery account.UserQuery
	mobile, err := strconv.ParseUint(params.Mobile, 10, 0)
	if err != nil {
		return response.CommonResponse[string]("转换失败", http.StatusBadRequest, userQuery.Password)
	}

	userQuery.Mobile = uint(mobile)
	//userQuery.Password = utility.MD5String(params.Password)
	user := account.GetUser(userQuery)
	if user.ID == 0 {
		var autoReg parameter.Register
		autoReg.Mobile = uint(mobile)
		autoReg.Password = "123456"
		us.Register(autoReg)
	}

	token, _ := utility.GenerateToken(nil, uint(user.ID), user.Username, user.Password)
	result := response.FormatUserInfo(user)
	data := struct {
		Token string         `json:"token"`
		User  response.Users `json:"user"`
	}{Token: token, User: result}

	return response.CommonResponse("登录成功", http.StatusOK, data)
}

// Logout 用户登出
func (us *UserLogin) Logout(token string) response.Response {
	utility.ForbiddenToken(token)

	return response.CommonResponse[bool]("登出成功", http.StatusOK, true)
}

// UserInfo 用户详情
func (us *UserLogin) UserInfo(id uint) response.Response {
	userInfo := account.GetUserById(id)

	result := response.FormatUserInfo(userInfo)

	return response.CommonResponse("获取成功", http.StatusOK, result)
}
